package mredis

import (
	"errors"
	"fmt"
)

var RedisConnError = errors.New("Not available redis connection.")
var RedisReplyEmptyError = errors.New("Redis replay empty.")

type Command struct {
	conn *RedisConn
	release func()
}

func (c *Command) Close() {
	if c.release != nil {
		c.release()
	}
}

// 打印给定的字符串
func(c *Command) Echo(str string) (string,error){
	if c.conn == nil {
		return "",RedisConnError
	}
	_,err := c.conn.WriteString(fmt.Sprintf("ECHO %s\r\n",str))
	if err != nil {
		return "",err
	}

	b,err := c.conn.ReadAsString()
	if err != nil {
		return "",err
	}
	return string(b),nil
}

//Ping 命令使用客户端向 Redis 服务器发送一个 PING ，如果服务器运作正常的话，会返回一个 PONG
func (c *Command) Ping() (error){
	if c.conn == nil {
		return RedisConnError
	}
	_,err := c.conn.WriteString("PING\r\n")
	if err != nil {
		return err
	}
	b,err := c.conn.ReadAsString()
	if err != nil {
		return err
	}
	if b != "PONG" {
		return RedisError("Unexpected response to PING.")
	}
	return nil
}
//Redis Quit 命令用于关闭与当前客户端与redis服务的连接。被关闭的连接，将不会再放入连接池
func (c *Command) Quit()(error){
	if c.conn == nil {
		return RedisConnError
	}
	_,err := c.conn.WriteString("QUIT\r\n")
	if err != nil {
		return err
	}
	b,err := c.conn.ReadAsString()
	if err != nil {
		return err
	}
	if b != "OK" {
		return RedisError("Unexpected response to Quit.")
	}
	return nil
}

func (c *Command) Select(db int) error {
	if c.conn == nil {
		return RedisConnError
	}
	if c.conn.db != db {
		_, err := c.conn.WriteString(fmt.Sprintf("SELECT %d\r\n", db))
		if err != nil {
			return err
		}
		b, err := c.conn.ReadAsString()
		if err != nil {
			return  err
		}
		if b != "OK" {
			return RedisError("Unexpected response to Select.")
		}

		c.conn.db = db
	}
	return nil
}
